package com.boge.store;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.time.Duration;
import java.util.List;

@Repository
public class RedisChatMemoryStore implements ChatMemoryStore {
    @Autowired
    private StringRedisTemplate template;

    private String preName="langchain4j:";
    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        //获取会话消息
        String str = template.opsForValue().get(preName+memoryId.toString());
        //把josn转为List
        List<ChatMessage> list = ChatMessageDeserializer.messagesFromJson(str);
        return list;
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
        //更新会话记忆
        //1、把list中的记忆转为json格式
        String str = ChatMessageSerializer.messagesToJson(list);
        //2、把json格式记忆存入redis，并设置过期时间为1天
        template.opsForValue().set(preName+memoryId.toString(),str, Duration.ofDays(1));
    }

    @Override
    public void deleteMessages(Object memoryId) {
        template.delete(preName+memoryId.toString());
    }
}
